package com.lechicanh.cgrid.ke.worker.worker;

import java.io.IOException;
import java.rmi.ConnectException;
import java.rmi.NotBoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.lechicanh.cgrid.ke.api.job.Job;
import com.lechicanh.cgrid.ke.api.message.Message;
import com.lechicanh.cgrid.ke.api.resource.Resource;
import com.lechicanh.cgrid.ke.api.resource.ServiceName;
import com.lechicanh.cgrid.ke.api.service.HandlerService;
import com.lechicanh.cgrid.ke.worker.worker.servicelookup.ServiceLookup;

public class WorkerManagement {
	private static final Logger m_logger = Logger.getLogger(WorkerManagement.class.getSimpleName());
	public static void start(String path, int port, String identifier) throws NotBoundException, InterruptedException, IOException{
		HandlerService service = null;
		try{
			System.out.println("Lookup hanlderService.....");
			service = ServiceLookup.lookup(path, port);
		}catch(ConnectException e){
			System.out.println("Lookup fail. It seems hanlderService does not exist or down, closing worker.");
			return;
		}
		service.register(identifier);
		while(true){
			Job job = service.free(identifier);
			if(job != null){
				String message = job.getMessage();
				List<String> result = new ArrayList<String>();
				if(Resource.NEW_JOB_MESSAGE.equals(message)){
					System.out.println("Receive new job with extract keywords from page " + job.getFromPage() + " to page " + job.getToPage());
					Long fromPage = job.getFromPage();
					Long toPage = job.getToPage();
					for(Long i = fromPage; i<= toPage; i++){
						System.out.println("Extracting keywords in page: " + i + ";)");
						List<String> list = new Worker(i).doJob();
						if(list != null ){
							System.out.println("Extracted succesfully keywords in page: " + i + " ;)");
							result.addAll(list);
						}else{
							System.out.println("Closing worker");
							return;
						}
					}
					System.out.println("Extracting keywords from page: " + fromPage + " to " + toPage + " is done");
					service.message(new Message(identifier, ServiceName.HANDLER_SERVICE, job.getId(), Resource.DONE_JOB_MESSAGE, result));
				}else if(Resource.NO_JOB_MESSAGE.equals(message)){
					System.out.println("No jobs need to be worked, closing worker");
					return;
				}else if(Resource.NOT_REGITERED_MESSAGE.equals(message)){
					System.out.println("Worker did not register in server, closing worker");
					return;
				}
			}
		}
	}
	
	public static void start(String path, String identifier) throws NotBoundException, InterruptedException, IOException{
		start(path, Resource.RMI_PORT, identifier);
	}

}
